﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class BinarySearch<C>
    {
        /// <summary>
        /// Binary search through a list. Searches as long as the list is not exhausted and the searched element is not found yet.
        /// </summary>
        /// <param name="list">the list to search through</param>
        /// <param name="criterion">the criterion from which we determine, whether we have found our element</param>
        /// <returns>the element, if it is found, or the default value of type C, if not</returns>
        public C find(List<C> list, Func<C, int> criterion)
        {

            C result = default(C);

            int mid;
            int left = 0;
            int right = list.Count - 1;

            

            while (left <= right)
            {
                mid = left + ((right - left) / 2);
                if (criterion(list[mid]) == 0)
                {
                    Console.WriteLine("GEFUNDEN");
                    result = list[mid];
                    return result;
                }
                else if (criterion(list[mid]) > 0)
                {
                    right = mid - 1;
                }
                else if (criterion(list[mid]) < 0)
                {
                    left = mid + 1;
                }

            }
            
           
            Console.WriteLine("NICHT GEFUNDEN");
            return result;


      
        }

    }
}
